package top.cardone.security.shiro.session.mgt.eis.impl;

import com.google.common.collect.Sets;
import lombok.Setter;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import top.cardone.cache.Cache;
import top.cardone.context.ApplicationContextHolder;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * Created by yht on 16-2-2.
 */
public class SessionDaoImpl extends AbstractSessionDAO {
	@Setter
	private String name = SessionDaoImpl.class.getName();

	@Override
	protected Serializable doCreate(Session session) {
		super.assignSessionId(session, super.generateSessionId(session));

		this.update(session);

		return session.getId();
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		return ApplicationContextHolder.getBean(Cache.class).get(Session.class, this.name, sessionId);
	}

	@Override
	public void update(Session session) throws UnknownSessionException {
		ApplicationContextHolder.getBean(Cache.class).put(this.name, session.getId(), session);
	}

	@Override
	public void delete(Session session) {
		ApplicationContextHolder.getBean(Cache.class).evict(this.name, session.getId());
	}

	@Override
	public Collection<Session> getActiveSessions() {
		List<? extends org.springframework.cache.Cache> caches = ApplicationContextHolder.getBean(Cache.class).getCaches(SessionDaoImpl.class.getName());

		if (org.apache.commons.collections.CollectionUtils.isEmpty(caches)) {
			return Sets.newHashSet();
		}

		for (org.springframework.cache.Cache cache : caches) {
			Object nativeCacheObject = cache.getNativeCache();

			if (nativeCacheObject instanceof com.google.common.cache.Cache) {
				com.google.common.cache.Cache guavaCache = (com.google.common.cache.Cache) nativeCacheObject;

				return guavaCache.asMap().values();
			}
		}

		return Sets.newHashSet();
	}
}